package com.zhentao.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhentao.mapper.ApCollectionMapper;
import com.zhentao.mapper.ArticleMapper;
import com.zhentao.model.article.dto.ArticleInfoDto;
import com.zhentao.model.article.dto.CollectionBehaviorDto;
import com.zhentao.model.article.pojo.ApArticle;
import com.zhentao.model.article.pojo.ApCollection;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.model.user.pojo.ApUser;
import com.zhentao.service.CollectionBehaviorService;
import com.zhentao.utils.common.AppUserThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class CollectionBehaviorServiceImpl implements CollectionBehaviorService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private ApCollectionMapper apCollectionMapper;
    @Autowired
    private RedisTemplate<String,String >redisTemplate;
    @Override
    public ResponseResult collectionNBehavior(CollectionBehaviorDto dto) {
        ApUser user = AppUserThreadLocalUtil.getUser();
        if(user== null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApArticle apArticle = articleMapper.selectById(dto.getEntryId());
        if(dto.getOperation()==0){
            apArticle.setCollection(apArticle.getCollection()+1);
            articleMapper.updateById(apArticle);
            ApCollection apCollection=new ApCollection();
            apCollection.setCollectionTime(new Date());
            apCollection.setType(dto.getType().intValue());
            apCollection.setArticleId(dto.getEntryId());
            apCollection.setPublishedTime(dto.getPublishedTime());
            apCollection.setEntryId(user.getId());
            apCollectionMapper.insert(apCollection);
            redisTemplate.opsForHash().put("collectionNBehavior"+dto.getEntryId().toString(),user.getId().toString(), JSON.toJSONString(dto));
        }else {
            apArticle.setCollection(apArticle.getCollection()-1);
            articleMapper.updateById(apArticle);
            LambdaQueryWrapper<ApCollection> wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(ApCollection::getEntryId, user.getId());
            wrapper.eq(ApCollection::getArticleId, dto.getEntryId());
            apCollectionMapper.delete(wrapper);
            redisTemplate.opsForHash().delete("collectionNBehavior"+dto.getEntryId().toString(),user.getId().toString());
        }
        return ResponseResult.okResult(200,"ok");
    }


}
